<?php
/**
 * 微信公众号相关接口
 * @copyright 许雷
 * @since v1.0,
 * https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
 *
 * */
class mygongzhonghao{
    public static $userInfo = "";
    public static $openId   = "";

    public static $qrUrl = "";
    public static $qrImage = "";


    //https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542
    //生成带来源的二维码
    /**
    http请求方式: POST
    URL: https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN
    POST数据格式：json
    POST数据例子：{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}}

    或者也可以使用以下POST数据创建字符串形式的二维码参数：
    {"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "test"}}}
     *
     *
     *
     */
    public static function createQR($sceneStr){
        $data = [
            "action_name"=> "QR_LIMIT_STR_SCENE",
            "action_info"=>["scene"=>["scene_str"=>$sceneStr]]
        ];


        $token = self::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$token";
        $json = json_decode(myspider::ajax($url,$data));
        //print_r(json_encode($json,JSON_PRETTY_PRINT));
        $qrUrl  = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($json->ticket);
        $result = myspider::get($qrUrl);
        $fileName = "up/".date("YmdHis").".jpg";
        file_put_contents(ROOT_PATH."web/".$fileName,$result);
        self::$qrUrl   = $json->url;
        self::$qrImage = $fileName;
        return $json;
    }



    //https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542
    //公众号服务号（订阅号不可以）生成带参数的二维码,临时二维码
    public static function qrTemp($scene,$page,$width){
        $token = mygongzhonghao::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$token";
        $time = 2592000;//30day
        $ajax = [
            "expire_seconds"=>$time,
            "action_name"=>"QR_STR_SCENE",
            "action_info"=>["scene"=>["scene_str"=>$scene]]
        ];

        $result = myspider::ajax($url,$ajax);
        $fileName = "up/qr_".date("YmdHis")."_".uniqid().".png";
        file_put_contents(ROOT_PATH."web/$fileName",$result);
        return $fileName;
    }

    //公众号服务号（订阅号不可以）生成带参数的二维码,永久二维码
    public static function qrForever($scene,$page,$width){
        $token = mygongzhonghao::getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";


    }

    /*
     * 文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
     * 获取用户基本信息（包括UnionID）
     * http请求方式: GET
     * https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
     *
     * 返回
     * {
            "subscribe": 1,
            "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
            "nickname": "Band",
            "sex": 1,
            "language": "zh_CN",
            "city": "广州",
            "province": "广东",
            "country": "中国",
            "headimgurl":"http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
            "subscribe_time": 1382694957,
            "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
            "remark": "",
            "groupid": 0,
            "tagid_list":[128,2],
            "subscribe_scene": "ADD_SCENE_QR_CODE",
            "qr_scene": 98765,
            "qr_scene_str": ""
        }
     * */
    public static function getUserInfo($openId){
        if((self::$openId != $openId) || (!self::$userInfo)){//新用户
            $accessToken = self::getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$accessToken}&openid={$openId}&lang=zh_CN";
            self::$userInfo =  json_decode(myspider::get($url));
            self::$openId = $openId;
        }

        return self::$userInfo;
    }

    public static function getUserJsonInfo($openId){
        return self::getUserInfo($openId);
    }

    public static function getNick($openId){
        $info = self::getUserInfo($openId);
        return $info->nickname;
    }

    //调用接口时，请登录“微信公众平台-开发-基本配置”提前将服务器IP地址添加到IP白名单中，点击查看设置方法，否则将无法调用成功。小程序无需配置IP白名单。
    //https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
    public static function getAccessToken() //获取access_token
    {
        $token = myredis::get("Token".WEIXIN_APPID);
        if($token) return $token;

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".WEIXIN_APPID."&secret=".WEIXIN_SECRET;
        $data = myspider::get($url);//通过自定义函数getCurl得到https的内容
        $resultArr = json_decode($data, true);//转为数组
        if(!$resultArr["access_token"]) {
            print_r($resultArr);
            die("can't get access_token");
        }

        myredis::set("Token".WEIXIN_APPID,$resultArr["access_token"],3600);
        return $resultArr["access_token"];//获取access_token
    }


    //查询公众号现在的菜单
    //文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141014
    //接口 https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN
    public static function queryMenu(){
        $accessToken = self::getAccessToken();
        $apiUrl = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=$accessToken";
        $result = myspider::get($apiUrl);
        return $result;
    }



    public static function createMenuByArray($array){
        return self::createMenuByJsonString(json_encode($array,JSON_UNESCAPED_UNICODE));
    }

    //创建公众号菜单,通过数组
    public static function createMenuByJsonString($jsonString){
        $accessToken = self::getAccessToken();
        $menuPostUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$accessToken;//POST的url
        return myspider::ajax($menuPostUrl,$jsonString);
    }

    public static function goLogin($callbackUrl=''){
        setcookie('QI_VIEW_ID',g('randId'),time()+3600*24*365*10);//保存回来的时候要看的页面
    
        if(!$callbackUrl) $callbackUrl = 'http://'.$_SERVER['HTTP_HOST'].'/'.COOKIE_DIR.'/index,callback';
        if(IS_LINUX){
                $redirectUrl = 'http://www.qilaiwan.com/login/?to='.base64_encode($callbackUrl);
                $encodeUrl  = urlencode($redirectUrl);
                $weixinUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.WEIXIN_APPID.'&redirect_uri='.$encodeUrl.'&response_type=code&scope='.WEIXIN_SCOPE.'&state=default#wechat_redirect';	
        }else{//windows 模拟测试
                $redirectUrl = 'http://local.www.qilaiwan.com/login/?to='.base64_encode($callbackUrl);
                $encodeUrl  = urlencode($redirectUrl);
                $weixinUrl =  'http://local.www.qilaiwan.com/login/index,getCode?appid='.WEIXIN_APPID.'&redirect_uri='.$encodeUrl.'&response_type=code&scope='.WEIXIN_SCOPE.'&state=default#wechat_redirect';	
        }
        myresponse::redirect($weixinUrl,0,'请授权微信登录');
    }

    
    //通过code获取openid和token
    public static function getTokenByCode($code){
		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.WEIXIN_APPID.'&secret='.WEIXIN_SECRET.'&code='.$code.'&grant_type=authorization_code';
        
		$result = myspider::fetch($url);
		$json   = json_decode($result);
        
        if('' == trim($json->openid)){//返回的openId不对
			mylogin::logout();
			myresponse::redirect('index,default',3,'请您授权微信登录');
		}
        
        return $json;
    }
    
    public static function getInfoByToken($token,$openId){
        	$url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openId.'&lang=zh_CN';
            $result = myspider::fetch($url);
            $userInfo   = json_decode($result);
            $userInfo->headimgurl = preg_replace("/\d+$/","46",$userInfo->headimgurl);
            
            return $userInfo;
    }

}
